#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void printids(const char *s) {
    pid_t pid = getpid();
    pthread_t tid = pthread_self();
    printf("%s pid=%u, tid=%u/%#x\n", s, pid, tid, tid );
}


void *thr_fn(void *arg) {
    printids(arg);
    return NULL;
}

void *thr_fn1(void *arg){
    printf("thread1 returning\n");
    return (void*)1;
}

void *thr_fn2(void *arg){
    printf("thread2 exiting\n");
    pthread_exit((void*)1);
}

void *thr_fn3(void *arg){
    while(1){
        printf("thread3 writing\n");
        sleep(1);
    }
}

int main(void)
{
    pthread_t tid;
    void *thr_ret = NULL;
    pthread_create(&tid, NULL, thr_fn, "new thread: ");
    printids("main thread:");
    sleep(1);
    pthread_create(&tid, NULL, thr_fn1, NULL);
    pthread_join(tid, &thr_ret);
    printf("thread1 return code:%d\n", thr_ret);
    pthread_create(&tid, NULL, thr_fn2, NULL);
    pthread_join(tid, &thr_ret);
    printf("thread1 exit code:%d\n", thr_ret);
    pthread_create(&tid, NULL, thr_fn3, NULL);
    sleep(3);
    pthread_cancel(tid);
    pthread_join(tid, &thr_ret);
    printf("thread3 cancled code:%d\n", thr_ret);
    return 0;
}
